import EventManager from "../Managers/EventManager";
import { EventTypes } from "../Managers/EventTypes";
import { SDKTools } from "../Managers/TaskSDK/SDKTools";
import { AudioSystem } from "../SystemAudio/AudioSystem";
import { StorageSystem } from "../SystemStorage/StorageSystem";
import SDK from "./SDK";

export class AliPaySDK extends SDK {

    onEvents() {
        super.onEvents();
        EventManager.on(EventTypes.GameEvents.GameRun, this.onGameRun, this);
        EventManager.on(EventTypes.GameEvents.GameOver, this.onGameOver, this);
    }
    private rewardedVideoOK: boolean = false;
    public init(callback?: Function, target?: any): void {
        let dat = { adUnitId: 'TEST_VIDEO', multiton: true }
        this.interstitialRewardedVideo = SDKTools.m_ADClass.createRewardedAd(dat);
        this.interstitialRewardedVideo.load();
        this.interstitialRewardedVideo.onLoad(() => {
            this.rewardedVideoOK = true;
        });
        super.init(callback, target);
    }

    protected setAdCfg(): void {
        this.adConfig.adBannerIdList = ["2300018563_03"];
        this.adConfig.adVideoIdList = [
            '2300018563_01',
        ];
        this.adConfig.adInterstitialId = "2300018563_02"; // 指定插屏广告ID
        this.adConfig.shareInfoArr = [{ title: "一起来挑战吧!", img: '' }]; // 自定义分享
        this.adConfig.app_key = "ks665406848553849654"
        uniSdk.AdPlat.instance.setBannerMaxShowTimes(60);
    }

    interstitialAd: any = null;
    interstitialRewardedVideo: any = null;
    bannerAd: any = null;
    protected async showBanner(): Promise<void> {
        console.log("showBanner");
        let param = {
            adUnitId: this.adConfig.adBannerIdList[0]
        };
        if (!this.bannerAd) {
            this.bannerAd = SDKTools.m_ADClass.createBannerAd(param);
        }
        this.bannerAd.onClose(res => {
            this.bannerAd.destroy();
            this.bannerAd = null;
        })
        this.bannerAd.onError(res => {
        })
        let p = await this.bannerAd.show();
    }
    protected hideBanner(): void {
        this.bannerAd && this.bannerAd.hide();
    }
    /**
       * 插屏广告
       */
    protected showInterstitial(d?: { success?: Function, fail?: Function, close?: Function }, cb2?) {
        console.log("showInterstitial");
        //触摸屏蔽
        // EventManager.emit(EventTypes.GameEvents.SetTouchMaskEnable,)
        let param = {
            adUnitId: this.adConfig.adInterstitialId
        };
        this.interstitialAd = SDKTools.m_ADClass.createInterstitialAd(param);
        if (this.interstitialAd) {
            this.interstitialAd.onClose(res => {
                // 插屏广告关闭事件 
                d && d.close && d.close();
                this.interstitialAd.destroy();
            })
            this.interstitialAd.onError(res => {
                // 插屏广告Error事件  
            })
            let p = this.interstitialAd.show()
            p.then(function (result) {
                // 插屏广告展示成功  
                console.log(`show interstitial ad success, result is ${result}`)
                d && d.success && d.success();
            }).catch(function (error) {
                // 插屏广告展示失败  
                console.log(`show interstitial ad failed, error is ${error.msg} ${error.code}`)
                d && d.fail && d.fail();
            })
        } else {
            console.log("创建插屏广告组件失败");
        }

    }

    /**
     * 显示原生模板广告
     */
    protected showCustomAd(adIndex: number, d?: { success?: Function, fail?: Function, close?: Function }) {

    }

    /**
       * 拉起激励视频广告
       */
    protected async showRewardedVideo(cb: Function | { success: Function, fail: Function, cancel: Function }, idx = 0) {
        let success = null;
        let fail = null;
        let cancel = null;
        if (typeof cb === 'object') {
            success = cb.success;
            fail = cb.fail;
            cancel = cb.cancel;
        } else {
            success = cb;
        }
        //暂停游戏
        EventManager.emit(EventTypes.GameEvents.GamePause);
        AudioSystem.pauseBGM();
        //
        console.warn('观看视频中');

        if (!this.interstitialRewardedVideo) {
            let dat = { adUnitId: 'TEST_VIDEO', multiton: true }
            this.interstitialRewardedVideo = SDKTools.m_ADClass.createRewardedAd(dat);
        }
        if (!this.rewardedVideoOK) {
            this.interstitialAd.onClose(res => {
                if (res.isEnded) {
                    console.log("激励视频已观看完毕 ");
                    success && success();
                    //恢复游戏
                    EventManager.emit(EventTypes.GameEvents.GameResume);
                    AudioSystem.resumeBGM();
                } else {
                    console.log("激励视频未观看完毕 ");
                    cancel && cancel();
                    EventManager.emit(EventTypes.GameEvents.GameResume);
                    AudioSystem.resumeBGM();
                }
            })
            this.interstitialRewardedVideo.onLoad(() => {
                this.rewardedVideoOK = true;
            })
            await this.interstitialRewardedVideo.load();
        }
        this.interstitialRewardedVideo.show()
        this.interstitialAd.onError(res => {
            console.log("激励视频加载失败 ");
            fail && fail();
            EventManager.emit(EventTypes.GameEvents.GameResume);
            AudioSystem.resumeBGM();
        })

    }


    //#region -------------事件---------------
    onGameRun() {
        let asset = StorageSystem.getData().levelAssets;
        this.reportAldStageStart(asset.curLv);
    }
    onGameOver(isWin) {
        let asset = StorageSystem.getData().levelAssets;

        if (isWin) {
            this.reportAldStageEnd(asset.curLv);
        } else {
            this.reportAldStageFail(asset.curLv);
        }
    }

    //#endregion
}